package com.itheima.pinda.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.pinda.DTO.user.CourierScopeDto;
import com.itheima.pinda.entity.user.PdCourierScope;
import com.itheima.pinda.mapper.PdCourierScopeMapper;
import com.itheima.pinda.mapstruct.AgencyDTO2Entity;
import com.itheima.pinda.service.PdCourierScopeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PdCourierScopeServiceImpl extends ServiceImpl<PdCourierScopeMapper, PdCourierScope> implements PdCourierScopeService {


    @Resource
    private AgencyDTO2Entity agencyDTO2Entity;

    /**
     * 批量保存快递员业务范围
     *
     * @param dtoList 快递员业务范围信息
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchSaveCourierScope(List<CourierScopeDto> dtoList) {
        List<PdCourierScope> pdCourierScopeList = dtoList.stream()
                .map(item -> agencyDTO2Entity.conver(item))
                .collect(Collectors.toList());

        return super.saveBatch(pdCourierScopeList);
    }


    /**
     * 删除快递员业务范围信息
     *
     * @param dto 参数
     * @return 是否删除成功
     */
    @Override
    public boolean deleteCourierScope(CourierScopeDto dto) {
        LambdaQueryWrapper<PdCourierScope> lambdaQuery = Wrappers.lambdaQuery();
        boolean canExecute = false;
        if (StringUtils.isNotBlank(dto.getAreaId())) {
            lambdaQuery.eq(PdCourierScope::getAreaId, dto.getAreaId());
            canExecute = true;
        }
        if (StringUtils.isNotBlank(dto.getUserId())) {
            lambdaQuery.eq(PdCourierScope::getUserId, dto.getUserId());
            canExecute = true;
        }

        return canExecute ? super.remove(lambdaQuery) : false;
    }


    /**
     * 获取快递员业务范围列表
     *
     * @param areaId 行政区域id
     * @param userId 快递员id
     * @return 快递员业务范围列表
     */
    @Override
    public List<CourierScopeDto> findAllCourierScope(String areaId, String userId) {
        List<PdCourierScope> pdCourierScopeList = super.list(Wrappers.<PdCourierScope>lambdaQuery()
                .eq(StringUtils.isNotBlank(areaId), PdCourierScope::getAreaId, areaId)
                .eq(StringUtils.isNotBlank(userId), PdCourierScope::getUserId, userId));

        return pdCourierScopeList.stream()
                .map(item -> agencyDTO2Entity.conver(item))
                .collect(Collectors.toList());
    }
}
